package com.jt.sp06zuui.filter;

import com.jt.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;



import javax.servlet.http.HttpServletRequest;

/**
 * 定义全局过滤器
 * @author 郭鲁政
 */
@Component
public class AccessFilter extends ZuulFilter {
    /**
     * 放在什么位置
     * @return
     */
    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 过滤器的顺序号
     * @return
     */
    @Override
    public int filterOrder() {
        //有五个默认的过滤器 把这个过滤器添加到末尾
        return 6;
    }

    /**
     * 针对当前请求,判断是否执行过滤代码
     * 调用item-service 检查是否登录
     * 否则不检查直接登录
     * @return true 要检查权限
     */
    @Override
    public boolean shouldFilter() {

        /**
         * 先获取请求上下文对象
         * 当前请求调用的服务ID
         * 调用的是否是item-service
         *
         */
        RequestContext context = RequestContext.getCurrentContext();
        String s = (String) context.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equals(s);
    }

    /**
     * 权限判断
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext con = RequestContext.getCurrentContext();
        HttpServletRequest request = con.getRequest();
        String header = request.getParameter("token");
        System.out.println(header);
        if (StringUtils.isBlank(header)){
            //阻止继续调用
            con.setSendZuulResponse(false);
            //直接返回响应
            con.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8") ;
            con.setResponseBody(JsonResult.err().code(401).msg("please login").toString());

        }
        /**
         * 当前zuul版本中,这个返回值没有使用
         */
        return null;
    }
}
